package com.wally.auth.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.wally.auth.util.AuthUtil;
import com.wally.auth.util.WxEnum;

@RestController
public class CallBackController {

	public static final Logger log = LoggerFactory.getLogger(CallBackController.class);

	@GetMapping("/callBack")
	public void callBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//TODO 第二步：通过code换取网页授权access_token
		String code = request.getParameter("code");
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
				+ "appid=" + WxEnum.APP_ID.getName()
				+ "&secret=" + WxEnum.APP_SECRET.getName()
				+ "&code=" + code
				+ "&grant_type=authorization_code";
		//第三步：刷新access_token（如果需要）
		//https://api.weixin.qq.com/sns/oauth2/refresh_token?
		//appid=APPID
		//&grant_type=refresh_token
		//&refresh_token=REFRESH_TOKEN

		JSONObject jsonObject = AuthUtil.doGetJson(url);
		String openid = jsonObject.getString("openid");
		String accessToken = jsonObject.getString("access_token");
		log.info("openid::" + openid);
		log.info("accessToken::" + accessToken);
		//TODO 第四步：拉取用户信息(需scope为 snsapi_userinfo)
		String infoUrl = "https://api.weixin.qq.com/sns/userinfo?"
				+ "access_token=" + accessToken 
				+ "&openid=" + openid
				+ "&lang=zh_CN";
		
		JSONObject info = AuthUtil.doGetJson(infoUrl);
		log.info(info.toString());
	}

}
